<template>
  <van-popup v-model:show="show" round position="bottom">
    <van-cascader
      v-model="cascaderValue"
      title="请选择所在地区"
      :options="options"
      :field-names="fieldNames"
      @close="show = false"
      @change="onChange"
      @finish="onFinish"
    />
  </van-popup>
</template>

<script setup lang="ts">
import { ref, defineProps, computed, defineEmits, onMounted, watch } from 'vue'
import { getLazyTree } from '../api/base/region'

interface Region {
  hasChildren: boolean
  id: string
  key: string
  parentId: string
  title: string
  value: string
  children: Region[]
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  modelValue: {
    type: String,
    default: '',
  },
  regionIds: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits([
  'update:visible',
  'update:modelValue',
  'update:regionIds',
  'onItemClick',
])

const show = computed({
  get() {
    return props.visible
  },
  set(val) {
    emit('update:visible', val)
  },
})

const fieldValue = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  },
})

const regionIds = computed({
  get() {
    return props.regionIds
  },
  set(val) {
    emit('update:regionIds', val)
  },
})

const cascaderValue = ref('')
const options = ref<Region[]>([])
const onChange = ({
  value,
  selectedOptions,
}: {
  value: string
  selectedOptions: Region[]
}) => {
  let current: Region | undefined

  if (Array.isArray(selectedOptions)) {
    current = selectedOptions[selectedOptions.length - 1]
  } else {
    current = options.value.find((item) => item.value === value)
  }

  if (!current?.hasChildren && current) {
    return
  }

  const parentCode = value || '00'

  getLazyTree(parentCode).then((res) => {
    const list = res.data.data.map((item: Region) => {
      return {
        ...item,
        leaf: !item.hasChildren,
      }
    })

    if (parentCode === '00') {
      options.value = list
    } else {
      if (current) {
        current.children = list
      }
    }
  })
}
const onFinish = ({ selectedOptions }: { selectedOptions: Region[] }) => {
  fieldValue.value = selectedOptions.map((option) => option.title).join('/')
  regionIds.value = selectedOptions.map((option) => option.value)
  const current = selectedOptions[selectedOptions.length - 1]

  if (!current?.hasChildren) {
    show.value = false
  }
}

const fieldNames = {
  text: 'title',
  value: 'value',
  children: 'children',
}

watch(show, (show) => {
  if (show) {
    // onChange({ value: '00', selectedOptions: [] })
  }
})

onMounted(() => {
  onChange({ value: '00', selectedOptions: [] })
})
</script>

<style lang="less" scoped></style>
